<?php

namespace App\Dao;

use App\Exceptions\SysExceptions;
use App\Model\ProjectPassModel;
use App\Model\ProjectsModel;
use App\Model\ProjectUserModel;
use App\Services\Logger;
use App\Services\PayServices;
use EasyWeChat\Kernel\Exceptions\InvalidArgumentException;
use EasyWeChat\Kernel\Exceptions\InvalidConfigException;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\DB;
use Mockery\Exception;

class ProjectDao extends BaseDao
{
    public static function get_projects_builder($params = []){
        $query = ProjectsModel::query();
        $query->when(checkIsHasField($params,'project_id'),function ($query)use ($params){
            $query->where('project_id',$params['project_id']);
        });

        $query->when(checkIsHasField($params,'category_id'),function ($query)use ($params){
            $query->where('category_id',$params['category_id']);
        });
        $query->when(checkIsHasField($params,'product_type'),function ($query)use ($params){
            $query->where('product_type',$params['product_type']);
        });
        return $query;
    }


    /**
     * @throws SysExceptions
     */
    public static function add_project($params = []){

//        $params['project_imgs'] = ;

        if(!checkIsHasField($params,'project_view_url')){
            self::error('请上传项目视频');
        }

        if(self::get_projects_builder()->create($params) === false){
            self::error('创建项目失败');
        }
    }

    public static function get_projects_page(array $all)
    {
        return self::get_projects_builder($all)->paginate();
    }

    public static function edit_project(array $all)
    {
        if(!checkIsHasField($all,'project_view_url')){
            self::error('请上传项目视频');
        }
        if(self::get_projects_builder([
            'project_id'=>self::deleteParamId($all,'project_id')
            ])->update(self::filterFields($all,new ProjectsModel())) === false){
            self::error('创建项目失败');
        }
    }

    public static function getOne(array $all,$type = 0)
    {
        $data =  self::get_projects_builder($all)->with('categoryInfo')->first();
        if($type == 1){
            $data['all_users'] = self::get_project_user_builder([
                'project_id'=>$all['project_id']
            ])->get();
            $data['me_canjia'] = self::get_project_user_builder([
                'project_id'=>$all['project_id'],
                'user_id'=>$all['b_user_id']
            ])->exists();
        }
        return $data;
    }

    public static function get_projects($params = [])
    {
        return self::get_projects_builder($params)->with('categoryInfo')->get();
    }




    public static function get_project_user_builder($params = []){
        $query = ProjectUserModel::query();

        $query->when(checkIsHasField($params,'project_id'),function ($query)use ($params){
            $query->where('project_id',$params['project_id']);
        });


        $query->when(checkIsHasField($params,'user_id'),function ($query)use ($params){
            $query->where('user_id',$params['user_id']);
        });


        $query->when(checkIsHasField($params,'order_no'),function ($query)use ($params){
            $query->where('order_no',$params['order_no']);
        });


        $query->when(checkIsHasField($params,'status'),function ($query)use ($params){
            $query->where('status',$params['status']);
        });

        $query->when(checkIsHasField($params,'id'),function ($query)use ($params){
            $query->where('id',$params['id']);
        });



        return $query;
    }


    /**
     * @throws InvalidArgumentException
     * @throws SysExceptions
     * @throws GuzzleException
     * @throws InvalidConfigException
     */
    public static function add_project_log($params = []): array
    {

        Logger::info("=====>");

        $info = self::get_projects_builder([
            'project_id'=>$params['project_id']
        ])->first();

        $params['order_json_data'] = json_encode($info,JSON_UNESCAPED_UNICODE);
        $params['price'] = $info['project_price'];
        $params['order_no'] = makeOrderNo();
        //获取推荐的用户
//        $params = array_merge(self::get_spread_id($params['user_id']),$params);
        if(self::get_project_user_builder()->create($params) === false){
            self::error('报名失败');
        }

        return PayServices::pay([
            'notify_url'=>route('notice_project'),
            'order_code'=>$params['order_no'],
            'price'=>$params['price'],
            'openid'=>UsersDao::get_user_builder([
                'user_id'=>$params['user_id']
            ])->value('openid')
        ]);
    }

    public static function get_spread_id($user_id = 0): array
    {
        $userInfo = UsersDao::getUserInfo([
            'user_id'=>$user_id
        ]);
        $zongjian_id = $userInfo['point_uid_spread_price_id'];
        if($userInfo['point_uid_spread_price_id'] == 0){
            $zongjian_id = UsersDao::get_user_builder([
                'user_id'=>$userInfo['spread_id']
            ])->value('point_uid_spread_price_id');
        }
        $data = [
            'spread_id'=>0,
            'product_price_uid'=>$zongjian_id
        ];
        //如果自己是合伙人
        if($userInfo['vip_index'] == 999){
            $data['spread_id'] = $userInfo['user_id'];
        }else{
            if($userInfo['spread_id'] != 0){
                $userSpreadInfo = UsersDao::getUserInfo([
                    'user_id'=>$userInfo['spread_id']
                ]);
                if($userSpreadInfo['vip_index'] == 999){
                    $data['spread_id'] = $userSpreadInfo['user_id'];
                }else{
                    $userSpreadInfo = UsersDao::getUserInfo([
                        'user_id'=>$userSpreadInfo['spread_id']
                    ]);
                    if($userSpreadInfo['vip_index'] == 999){
                        $data['spread_id'] = $userSpreadInfo['user_id'];
                    }
                }
            }
        }
        return $data;
    }

    /**
     * @throws SysExceptions
     */
    public static function changeProject($out_trade_no)
    {
        Logger::pay_notice("====>",[
            $out_trade_no
        ]);


        $query = self::get_project_user_builder([
            'order_no'=>$out_trade_no,
            'status'=>0
        ]);
        if(!$query->exists()){
            self::error('失败');
        }
        $info = $query->first()->toArray();
        //揭开json

        if($query->update(['status'=>1]) === false){
            self::error('失败');
        }
        self::changeDataUper($info['id']);

    }


    /**
     * @throws SysExceptions
     */
    public static function changeDataUper($order_id = 0): void
    {

        Logger::pay_notice("用户返费",[
            $order_id
        ]);
        //查询订单
        $project_info = ProjectDao::get_project_user_builder([
            'id'=>$order_id,
            'status'=>1
        ]);



        if(!$project_info->exists()){
            self::error('订单不存在');
        }
        $project_info = $project_info->first()->toArray();
        //用户user_id
        $user_id = $project_info['user_id'];
        $userInfo = UsersDao::get_user_builder([
            'user_id'=>$user_id
        ]);
        DB::beginTransaction();
        //存在
        try {
            if($userInfo->exists()){
                //修改成反润成功
                ProjectDao::get_project_user_builder([
                    'id'=>$order_id,
                    'status'=>1
                ])->update([
                   'status'=>2
                ]);
                $userInfo = $userInfo->first()->toArray();
                //存在上级
                if($userInfo['spread_id'] != 0){
                    //上级
                    $spread_info = UsersDao::get_user_builder([
                        'user_id'=>$userInfo['spread_id']
                    ])->first()->toArray();
                    //如果等级大于0(给上级返钱)
                    if($spread_info['vip_level_index'] > 0){
                        $order_json_data_origin = json_decode($project_info['order_json_data'],true);
                        //给直推将
                        $price_spread = $order_json_data_origin['project_price_spread'];
                        //下级有两个老板才能拿全部
                        $order_count = UsersDao::get_user_builder([
                            'spread_id'=>$spread_info['user_id']
                        ])->whereIn('vip_level_index',[3,4])->count();
                        if($order_count < 2){
                            BillDao::moneyNums($spread_info['user_id'],(bcmul($price_spread,0.8,2)),'奖励直推('.$project_info['user_id'].')',9998);
                            //奖励20%到扶持基金
                            BillDao::dMoneyNums($spread_info['user_id'],(bcmul($price_spread,0.2,2)),'奖励直推('.$project_info['user_id'].'扶持基金)',9997);
                        }else{
                            BillDao::moneyNums($spread_info['user_id'],$price_spread,'奖励直推('.$project_info['user_id'].')',9998);
                        }

                    }
                    //见点奖=>找到上级的老板
                    $spread_id = $spread_info['spread_id'];
                    while(true){
                        if($spread_id == 0){
                            break;
                        }
                        $sprea_spread_info = UsersDao::get_user_builder([
                            'user_id'=>$spread_id
                        ])->first()->toArray();
                        //是老板或者普通老板
                        if($sprea_spread_info['vip_level_index'] > 2 && $sprea_spread_info['vip_level_index'] < 5){
                            break;
                        }
                        $spread_id = $sprea_spread_info['spread_id'];
                    }
                    //是老板见点
                    if($spread_id > 0){
                        $order_json_data_origin = json_decode($project_info['order_json_data'],true);
                        //给见点奖
                        $price_spread = $order_json_data_origin['project_zongjian_price'];
                        //见点奖奖励()
                        BillDao::moneyNums($spread_id,$price_spread,'奖励见点奖('.$project_info['user_id'].')',9998);
                    }



                    //对我上级进行升级操作并且可能释放扶持基金=>修改对应等级
                    $order_json_data_origin = json_decode($project_info['order_json_data'],true);
                    //大于当前等级才升级
                    if($order_json_data_origin['vip_level_index'] > $userInfo['vip_level_index']){
                        UsersDao::get_user_builder([
                            'user_id'=>$user_id
                        ])->update([
                            'vip_level_index'=>$order_json_data_origin['vip_level_index']
                        ]);
                    }

                    //查询直推下级并且可能进行升级(直推可能升级为老板)
                    if($spread_info['vip_level_index'] < 3){
                        $vip_level_index = 1;
                        $u_vip_level_index = 3;
                        //普通代理
                        if($spread_info['vip_level_index'] == 2){
                            $vip_level_index = 2;
                            $u_vip_level_index = 4;
                        }
                        $count = UsersDao::get_user_builder([
                            'vip_level_index'=>$vip_level_index,
                            'spread_id'=>$spread_info['user_id']
                        ])->count();
                        //修改上级的用户等级为对应老板
                        if($count >= 2){
                            UsersDao::get_user_builder([
                                'user_id'=>$spread_info['user_id']
                            ])->update([
                                'vip_level_index'=>$u_vip_level_index
                            ]);
                            //释放扶持基金

                        }
                    }
                }
            }
            DB::commit();
        }catch (Exception $exception){
           DB::rollBack();
           self::error($exception->getMessage());
        }


    }

    public static function del_project(array $params)
    {
        if(self::get_projects_builder([
            'project_id'=>$params['id']
        ])->delete() === false){
            self::error('删除失败');
        }
    }

    /**
     * @param $params
     * @return Builder
     */
    private static function get_project_pass_builder($params = []): Builder
    {
        $query = ProjectPassModel::query();

        $query->when(checkIsHasField($params,'user_id'),function ($query)use ($params){
            $query->where('user_id',$params['user_id']);
        });
        $query->when(checkIsHasField($params,'project_id'),function ($query)use ($params){
            $query->where('project_id',$params['project_id']);
        });
        $query->when(checkIsHasField($params,'project_pass_value'),function ($query)use ($params){
            $query->where('project_pass_value',$params['project_pass_value']);
        });
        $query->when(checkIsHasField($params,'order_id'),function ($query)use ($params){
            $query->where('order_id',$params['order_id']);
        });

        $query->when(checkIsHasField($params,'project_pass_id'),function ($query)use ($params){
            $query->where('project_pass_id',$params['project_pass_id']);
        });


        return $query;
    }

    public static function get_project_pass_page(): \Illuminate\Contracts\Pagination\LengthAwarePaginator
    {
        return self::get_project_pass_builder()->with('userInfo')->paginate();
    }

    /**
     * @throws SysExceptions
     */
    public static function add_project_pass_value(array $params)
    {
        if(self::get_project_pass_builder([
            'project_pass_value'=>$params['project_pass_value'],
        ])->exists()){
            self::error('存在相同的卡密');
        }


        if(self::get_project_pass_builder()->create($params) === false){
            self::error('卡密添加失败');
        }
    }

    public static function del_project_pass(array $all)
    {
        if(self::get_project_pass_builder([
            'project_pass_id'=>$all['id']
        ])->delete() === false){
            self::error('删除失败');
        }
    }

    public static function get_project_pass_list()
    {
        return self::get_project_pass_builder()->where('user_id',0)->get();
    }

    /**
     * @throws SysExceptions
     */
    public static function recive_pass(array $params)
    {
        if(!checkIsHasField($params,'order_id')){
                self::error('订单id不存在');
        }

        if(self::get_project_pass_builder([
            'order_id'=>$params['order_id'],
            'user_id'=>$params['user_id']
        ])->exists()){
            self::error('此订单已经领取卡密了');
        }
        $orderInfo = self::get_project_user_builder([
            'id'=>$params['order_id']
        ])->first();
        if($orderInfo['status'] != 2){
            self::error('订单不正确');
        }
        $params['project_id'] = $orderInfo['project_id'];

        if(!self::get_project_pass_builder([
            'project_id'=>$params['project_id']
        ])->where('user_id',0)->exists()){
            self::error('此项目卡密不全');
        }

        if(self::get_project_pass_builder([
            'user_id'=>0
        ])->limit(1)->update([
            'user_id'=>$params['user_id'],
            'order_id'=>$params['order_id'],
            'recive_time'=>time()
        ]) === false){
            self::error('领取失败');
        }

    }

    public static function get_projects_log(array $array)
    {
        return self::get_project_user_builder([
            'user_id'=>getUserToken()
        ])->where('status','>',0)->with('passInfo')->get();
    }


}
